/**
    @author: administrator
    @date:   2020/12/8
    @note:
**/
package model

import (
	"net"
	"net/http"
	"net/url"
	"strings"
	"time"
)

//用户信息
type UserInfo struct {
	Id        uint64 `json:"id"`         //用户id
	Nickname  string `json:"nickname"`   //用户昵称
	Image     string `json:"image"`      //用户头像
	LoginTime string `json:"login_time"` //登陆的时间
	Ip        string `json:"ip"`
}

//使用连接 创建一个用户
func (u UserInfo) CreateUserInfo(query url.Values, ip string, user User) (Info UserInfo) {

	/*img := query.Get("img")
	if img == "" {
		img = "http://127.0.0.1:5001/html/image/miao.jpeg"
	}*/
	t := time.Now().Unix() //现行时间戳
	return UserInfo{
		Id:       user.ID,
		Nickname: user.LoginName,
		Image:    "",

		LoginTime: time.Unix(t, 0).Format("2006-01-02 15:04:05"),
		Ip:        ip,
	}
}

//获取ip
func GetLocalIP() string {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return ""
	}

	for _, address := range addrs {
		// 检查ip地址判断是否回环地址
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				return ipnet.IP.String()
			}
		}
	}
	return ""
}

//获取客户端ip
func ClientPublicIP(r *http.Request) string {
	var ip string
	for _, ip = range strings.Split(r.Header.Get("X-Forwarded-For"), ",") {
		ip = strings.TrimSpace(ip)
		if ip != "" {
			return ip
		}
	}

	ip = strings.TrimSpace(r.Header.Get("X-Real-Ip"))
	if ip != "" {
		return ip
	}

	if ip, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)); err == nil {
		return ip
	}

	return ""
}
